//
//  PlayerManager.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/4/13.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "PlayerManager.h"
#import "Track.h"
#import "DOUAudioStreamer.h"

static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;

@import AVFoundation;
@interface PlayerManager()

@property (nonatomic, strong)DOUAudioStreamer * player;
@property (nonatomic, strong)id  timeObserver;
@property (nonatomic)BOOL isEnterBackground;
@property (nonatomic)BOOL seekToZeroBeforePlay;

@property (nonatomic)BOOL isAnswerVieo;//区分一下  音频播放  和  问题答案播放   （因为 问题答案无是否连续这一说）

@end
@implementation PlayerManager


+ (instancetype)shareManeger {
    
    
    static PlayerManager *manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];

    });
    return manager;
}


//记录播放期间 后台杀死 时候的时间
- (void)saveCurrentPlayingTime {
    
}

//在播放期间被电话 微信 打断的处理
- (void)handleInterreption:(NSNotification *)sender {
    
    NSDictionary *info = sender.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        [self pause];
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            [self play];
            
        }
    }
    
}
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
    
}

- (void)playAnswerVideoWith:(NSString *)url {
    
    self.isAnswerVieo = YES;
    [self cancelPlayer];
    
    Track *track = [[Track alloc] init];
    
    NSURL * playURL = [NSURL URLWithString:url];
    
    track.audioFileURL = playURL;
    _player = [DOUAudioStreamer streamerWithAudioFile:track];
    self.currentURL = url;
    
    [self initPlayer];
    [self play];
    [self setupHintForPlayerWith:track];
}

//播放音频的方法
- (void)playMusic:(NSString *)url withIsPlay:(BOOL) isImmediately{
    
    self.isAnswerVieo = NO;
    if ( [url isEqualToString:self.currentURL] && !_isPlay)
    {
        //[self play];
        IGLog(@"%@当前已是该播放源",url);
        return;
    }
    else
    {
        [self cancelPlayer];
        
        Track *track = [[Track alloc] init];
        
        
        NSString *localPath = [[DownloadManager sharedManager] localFilePathForURLString:url];

        NSURL * playURL = [NSURL URLWithString:url];
        if (localPath.length > 0) {
            playURL = [NSURL fileURLWithPath:localPath];
        }
        
        track.audioFileURL = playURL;
        _player = [DOUAudioStreamer streamerWithAudioFile:track];
        self.currentURL = url;
        
        [self initPlayer];
        if (isImmediately) {
            [self play];
        }
        
        [self setupHintForPlayerWith:track];
        
    }
    
}

-(void)resetMusic {
    
    
    [self cancelPlayer];
    Track *track = [[Track alloc] init];
    
    NSString *localPath = [[DownloadManager sharedManager] localFilePathForURLString:self.currentURL];
    
    NSURL * playURL = [NSURL URLWithString:self.currentURL];
    if (localPath.length > 0) {
        playURL = [NSURL fileURLWithPath:localPath];
    }
    track.audioFileURL = playURL;
    _player = [DOUAudioStreamer streamerWithAudioFile:track];

    [self initPlayer];
    [self setupHintForPlayerWith:track];
}

- (void)setupHintForPlayerWith:(Track *)track
{

    [DOUAudioStreamer setHintWithAudioFile:track];
}
- (void)cancelPlayer
{
    if (_player != nil) {
        [self pause];
        [_player removeObserver:self forKeyPath:@"status"];
        [_player removeObserver:self forKeyPath:@"duration"];
        [_player removeObserver:self forKeyPath:@"bufferingRatio"];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
        
        _player = nil;
    }
    [_timer invalidate];
    [self updateCurrentPlayStatus:AVPlayerPlayStatePause];
    self.isPlay = NO;
    [_player stop];

}

- (void)initPlayer {
    
    [_player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_player addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_player addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
    
    if (![AppManager sharedManager].isOffReceiverWhenListen) {
        //监听是否靠近耳朵
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
    }
   
   // [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; //开启红外感应
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
     [_timer setFireDate:[NSDate distantFuture]];
    [_player setVolume:2.];
}

-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        
       
        if ([[UIDevice currentDevice] proximityState] == YES)
        {
            
            //靠近耳朵
            [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        }
        else
        {
            //远离耳朵
            [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
        }

    });
}

//调整播放进度
- (void)musicSeekToTime:(float)time {
    

    if ([_player duration]) {
        [_player setCurrentTime:[_player duration] * time];
        
        self.progress = time;
    }else {
        [_player setCurrentTime:0.0f];
        self.progress = 0;
    }
    

}

//停止

- (void)stop {
    
    [_timer invalidate];
    [self updateCurrentPlayStatus:AVPlayerPlayStatePause];
    self.isPlay = NO;
    self.currentURL = nil;
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
    [_player stop];
}

//暂停播放
- (void)pause {
    self.isPlay = false;
    [_timer setFireDate:[NSDate distantFuture]];
    [self updateCurrentPlayStatus:AVPlayerPlayStatePause];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    [_player pause];
}

//播放
- (void)play {
    
    IGLog(@"-----url------%@",self.player.audioFile.audioFileURL.absoluteString);
    
    if ([self.player.audioFile.audioFileURL.absoluteString hasPrefix:@"http"]) {
        
        if (![AppManager sharedManager].allowWhenPlay && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
            
            [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_COMMIT", nil) commit:^{
                
                [AppManager sharedManager].allowWhenPlay = YES;
                
                [_timer setFireDate:[NSDate distantPast]];
                [self updateCurrentPlayStatus:AVPlayerPlayStatePlaying];
                self.isPlay = true;
                [_player play];
                
            } cancel:nil];
            
            return;
        }

    }
    
    [_timer setFireDate:[NSDate distantPast]];
    [self updateCurrentPlayStatus:AVPlayerPlayStatePlaying];
    self.isPlay = true;
    
    if (![AppManager sharedManager].isOffReceiverWhenListen) {
        [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    }
    
    [_player play];
}


- (void)timerAction:(id)timer
{
    
    if ([_player duration] == 0.0 ) {
        if (_delegate && [_delegate respondsToSelector:@selector(updateProgressWith:)]) {
            [_delegate updateProgressWith:0.0];
        
        }
    }
    else {
        
        if (_delegate && [_delegate respondsToSelector:@selector(updateProgressWith:)]) {
            
         [_delegate updateProgressWith:[_player currentTime] / [_player duration]];
            
            IGLog(@"%f------%f",[_player currentTime],[_player duration]);
        }
    }
    
    
}

- (void)updateStatus
{
    switch ([_player status]) {
        case DOUAudioStreamerPlaying:
            
            [self updateCurrentPlayStatus:AVPlayerPlayStatePlaying];
            self.isPlay = YES;
            break;
            
        case DOUAudioStreamerPaused:
            [self updateCurrentPlayStatus:AVPlayerPlayStatePause];
            self.isPlay = NO;
            break;
            
        case DOUAudioStreamerIdle:
            [self updateCurrentPlayStatus:AVPlayerPlayStateNotKnow];
            self.isPlay = NO;
            break;
            
        case DOUAudioStreamerFinished:
            
            [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
            self.isPlay = NO;
            
            [self resetMusic];
             [self updateCurrentPlayStatus:AVPlayerPlayStateEnd];
            
            break;
            
        case DOUAudioStreamerBuffering:
            [self updateCurrentPlayStatus:AVPlayerPlayStateBufferEmpty];
            break;
            
        case DOUAudioStreamerError:
            [self updateCurrentPlayStatus:AVPlayerPlayStateNotPlay];
            break;
    }
}
#pragma mark - kvo

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kDurationKVOKey) {
        [self performSelector:@selector(timerAction:)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
//    else if (context == kBufferingRatioKVOKey) {
//        [self performSelector:@selector(updateBufferingProgress)
//                     onThread:[NSThread mainThread]
//                   withObject:nil
//                waitUntilDone:NO];
//    }
//   else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
}



- (void)updateCurrentPlayStatus:(AVPlayerPlayState)state {
    IGLog(@"-----%@---%@",self.currentURL, @(state));
    
    if (self.currentURL) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kPlayManagerState  object:nil userInfo:@{kPlayManagerState : @(state),kCurrentPlayURL:self.currentURL}];
    }else{
         [[NSNotificationCenter defaultCenter] postNotificationName:kPlayManagerState  object:nil userInfo:@{kPlayManagerState : @(state),kCurrentPlayURL:@"nil"}];
    }
    
}
- (void)avplayerFalileWith:(NSError *)error{
    

    if (!error) {
        return;
    }
    [self updateCurrentPlayStatus:AVPlayerPlayStateNotPlay];
    /* Display the error. */
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:[IGUtils tipFromError:error]
                                                       delegate:nil
                                              cancelButtonTitle:MYLocalizedString(@"PUBLIC_OK", nil)
                                              otherButtonTitles:nil];
    [alertView show];
}
- (NSString *)currentTime {
    //当前播放进度
    NSTimeInterval current = self.player.currentTime;
    
    IGLog(@"----%f",current);
    return [self timeFormatted:(int)current];
}

- (NSTimeInterval)totaltime {
    if (_player.duration) {
        _totaltime = _player.duration;
    }else {
        _totaltime = 0;
    }
    

    return _totaltime;
}
- (NSString *)durantion {
    //视频总长度
    NSTimeInterval total = _player.duration  - _player.currentTime;
    return [self timeFormatted:abs((int)total)];
}

#pragma mark - 时间转换

- (NSString *)timeFormatted:(int)totalSeconds {
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60);
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

@end
